
var express = require('express')
var db = require('../db.js')
var router = express.Router()
var md5 = require('md5-nodejs')
var multer = require('multer');

var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})

// 获取用户
router.get('/getuser', async function (req, res) {
    var sql = `select * from user`;
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

// 新增用户
router.post('/saveUser', urlencodedParser, async function (req, res) {
    let {
        loginName, loginKey
    } = req.body
    var sql = `insert into user (loginName, loginKey) values ('${loginName}','${loginKey}')`;
    // console.log(req.body)
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

//修改地址
router.post('/xgdizhi', urlencodedParser, async function (req, res) {
    let {
        id, area
    } = req.body
    var sql = `update user set  area='${area}' where id=${id}`;
    const {
        data
    } = await db.doSQL(sql)
    // console.log(data)
    res.send(db.handerResult(data))
})

//修改用户名和密码
router.post('/xgUser', urlencodedParser, async function (req, res) {
    let {
        id, loginName, loginKey
    } = req.body
    var sql = `update user set loginName='${loginName}', loginKey='${loginKey}' where id=${id}`;
    const {
        data
    } = await db.doSQL(sql)
    // console.log(data)
    res.send(db.handerResult(data))
})

//删除用户
router.get('/delUser', urlencodedParser, async function (req, res) {
    let {
        id
    } = req.query
    var sql = `delete from user where id=${id}`;
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerDelete(data))
})

// 个人中心--修改新密码
router.post('/newPassword', urlencodedParser, async function (req, res) {
    var {
        loginKey,
        id
    } = req.body
    var sql = `update user set loginKey='${loginKey}' where id='${id}'`
    const {
        data
    } = await db.doSQL(sql)
    if (data.changedRows == 1) {
        res.send(db.handerResult(data))
    } else {
        res.send(db.errorResult(data))
    }
})

// 个人中心--密码修改--判断旧密码
router.get('/changePassword', async function (req, res) {
    var {
        id
    } = req.query
    var sql = `select loginKey from user where id='${id}'`
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

// 修改账户信息
router.post('/account', urlencodedParser, async function (req, res) {
    var {
        id,
        name,
        age,
        edu,
        gender
    } = req.body
    var sql = `update user set name='${name}',age='${age}',edu='${edu}',gender='${gender}' where id='${id}'`
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

// 注册pc 
router.post('/registers', urlencodedParser, async function (req, res) {
    var {
        loginName,
        loginKey,
    } = req.body;
    // console.log(req.body);
    var sql = `insert into user (loginName, loginKey) values ('${loginName}','${loginKey}')`
    const data = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

//小程序注册
router.post('/wx-registers', urlencodedParser, async function (req, res) {
    var {
        name,
        loginName,
        loginKey,
    } = req.body;
    // console.log(req.body);
    var sql = `insert into user (name,loginName, loginKey) values ('${name}','${loginName}','${loginKey}')`
    const data = await db.doSQL(sql)
    res.send(db.handerResult(data))
})

// info请求
router.get('/info', async function (req, res) {
    var {
        token
    } = req.query
    var sql = `select u.id,u.loginKey,u.loginName,u.area,u.age,u.gender,u.edu, name ,name from token as t, user as u where t.uid = u.id and t.token = '${token}'; `
    const r = await db.doSQL(sql)
    if (r.data[0]) {
        res.send(db.handerResult(r.data[0]))
    } else {
        res.send(db.noHanderResult())
    }
})
// 退出
router.post('/logout', urlencodedParser, async function (req, res) {
    let { token } = req.body
    let sql = "delete from token where token=?"
    let r = await db.doSQL(sql, [token])
    if (r.data.affectedRows == 0) {
        res.send(db.errorResult({}))
    } else {
        res.send(db.handerdata({}))
    }

})

// 小程序登录
router.post('/mpLogin', urlencodedParser, async function (req, res) {
    var {
        loginName,
        loginKey
    } = req.body
    // console.log(loginName);
    // console.log(loginKey);
    var sql = "select id,name,loginName,status from user where loginName=? and loginKey=?"
    const r = await db.doSQL(sql, [loginName, loginKey])
    if (r.data[0]) {
        res.send(db.handerResult(r.data[0]))
    } else {
        res.send(db.noHanderResult())
    }
})


// 登录
router.post('/login', urlencodedParser, async function (req, res) {
    // 无token之前
    // var { loginName, loginKey } = req.body
    // var sql = "select id,name,gender,loginName,roles,status,avatar from users where loginName=? and loginKey=?"
    // const r = await db.doSQL(sql, [loginName, loginKey])
    // res.send(db.handerResult(r.data))
    // 有token
    var {
        loginName,
        loginKey
    } = req.body
    // var sql = "select id,name,loginName,status, from user where loginName=? and loginKey=?"
    var sql = `select id,name,loginName,status from user where loginName='${loginName}' and loginKey='${loginKey}'`
    // var sql = "select id from users where loginName=? and loginKey=?"
    // const r = await db.doSQL(sql, [loginName, loginKey])
    const r = await db.doSQL(sql)
    // console.log(r)
    // 判断用户名与密码是否匹配->if匹配,将id传给token
    if (r.data[0]) {
        // 将id传给token
        const token = await tokenFn(r.data[0].id)
        // 用户在登录时先判断有没token，没有则不能登录
        // console.log(token)
        if (token) {
            r.data[0].token = token
            res.send(db.handerResult(r.data[0]))
        } else {
            // ...
        }
    } else {
        res.send(db.noHanderResult())
    }
})
// token
async function tokenFn(uid) {
    // 查询token数据表
    var sql = "select * from token where uid=?"
    const res = await db.doSQL(sql, [uid])
    let token;
    // 判断有无token-->如果无,生成新token,有的话直接等于原来的token
    if (res.data.length == 0) {
        // 无token时
        // 生成32位字符串
        let newToken = md5('zxwx' + uid + Date.now())
        // 新增token
        const sql = "insert into token (token,uid) values (?,?)"
        const {
            data
        } = await db.doSQL(sql, [newToken, uid])
        // 判断token是否新增成功
        if (data.affectedRows == 1) {
            token = newToken
        } else {
            token = null
        }
    } else {
        // 有token时
        token = res.data[0].token
    }
    return token
}


module.exports = router;